//
//  JCClubEventVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/18.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCClubEventVC.h"
#import "ClubsSetting.h"
#import "JCEventDetailVC.h"
#import "JCClubEventModel.h"
#import "JCClubApi.h"
#import "JCClubEventCell.h"
#import "UIScrollView+YFMJRefresh.h"

@interface JCClubEventVC ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIButton *pushBtn;
@property (weak, nonatomic) IBOutlet UIButton *joinBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray <JCClubEventModel *> *eventArray;
@property (assign, nonatomic) NSInteger pageIndex;
@end

@implementation JCClubEventVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([User getUseInfo].adminClubs.count > 0) {
        CGRect frame = _headerView.frame;
        frame.size.height = 0;
        _headerView.frame = frame;
        [_tableView beginUpdates];
        [_tableView setTableHeaderView:_headerView];
        [_tableView endUpdates];
        _headerView.alpha = 0;
        _pushBtn.hidden = NO;
    }else if ([User getUseInfo].joinClubs.count > 0){
        CGRect frame = _headerView.frame;
        frame.size.height = 0;
        _headerView.frame = frame;
        [_tableView beginUpdates];
        [_tableView setTableHeaderView:_headerView];
        [_tableView endUpdates];
        _headerView.alpha = 0;
        _pushBtn.hidden = YES;
    }else{
        _pushBtn.hidden = YES;
    }
}

- (void)initCode{
    _pushBtn.layer.cornerRadius =
    _joinBtn.layer.cornerRadius = 3;
    _joinBtn.layer.masksToBounds =
    _pushBtn.layer.masksToBounds = YES;
    
    __weak typeof(self)weakSelf = self;
    _eventArray = [NSMutableArray array];
    [_tableView addLegendHeaderWithShowTime:NO RefreshingBlock:^{
         weakSelf.pageIndex = 1;
        [weakSelf loadData];
    }];
    [_tableView addNormalFooterWithRefreshingBlock:^{
        [weakSelf loadMore];
    }];
}

- (void)loadData{
    __weak typeof(self)weakSelf = self;
    _pageIndex = 1;
    NSString *clubID;
    if ([User getUseInfo].adminClubs.count > 0) {
        clubID = [User getUseInfo].adminClubs.firstObject.clubID;
    }else if ([User getUseInfo].joinClubs.count > 0){
        clubID = [User getUseInfo].joinClubs.firstObject.clubID;
    }else{
        clubID = @"0";
    }
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi getClubEventListWithClubID:clubID page:_pageIndex complete:^(NSError *error, NSArray<JCClubEventModel *> *eventList) {
        [weakSelf.tableView.mj_header endRefreshing];
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            [weakSelf.hud dismiss];
            [weakSelf.eventArray removeAllObjects];
            JCClubEventModel *guideModel = [JCClubEventModel new];
            guideModel.eventID = @"GUIDE";
            guideModel.creatTime =
            guideModel.startTime = @"2018-01-01";
            guideModel.content = @"";
            guideModel.title = @"Squash Spark Club User Guide";
            [weakSelf.eventArray addObject:guideModel];
            [weakSelf.eventArray addObjectsFromArray:eventList];
            [weakSelf.tableView reloadData];
        }
    }];
}

- (void)loadMore{
    __weak typeof(self)weakSelf = self;
    _pageIndex++;
    NSString *clubID;
    if ([User getUseInfo].adminClubs.count > 0) {
        clubID = [User getUseInfo].adminClubs.firstObject.clubID;
    }else if ([User getUseInfo].joinClubs.count > 0){
        clubID = [User getUseInfo].joinClubs.firstObject.clubID;
    }else{
        clubID = @"0";
    }
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi getClubEventListWithClubID:clubID page:_pageIndex complete:^(NSError *error, NSArray<JCClubEventModel *> *eventList){
        [weakSelf.tableView.mj_footer endRefreshing];
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            weakSelf.pageIndex -= 1;
        }else{
            [weakSelf.hud dismiss];
            if (eventList.count == 0) {
                weakSelf.pageIndex -= 1;
                [weakSelf.hud showString:@"No More Data" dimissAfterSecond:1];
            }else{
                [weakSelf.eventArray addObjectsFromArray:eventList];
                [weakSelf.tableView reloadData];
            }
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _eventArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JCClubEventCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JCClubEventCell" forIndexPath:indexPath];
    cell.eventModel = _eventArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    JCClubEventModel *model = _eventArray[indexPath.row];
    if ([model.eventID isEqualToString:@"GUIDE"]) {
        [self performSegueWithIdentifier:kSegueClubPushEventExplain sender:model];
    }else{
        [self performSegueWithIdentifier:kSegueClubPushEventDetail sender:model];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[User getUseInfo] clubUserType] == ClubUserTypeAdmin) {
        JCClubEventModel *model = _eventArray[indexPath.row];
        if ([model.eventID isEqualToString:@"GUIDE"]) {
            return NO;
        }else{
            return YES;
        }
    }else{
        return NO;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"Delete";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self)weakSelf = self;
    FUIAlertView *alert = [FUIAlertView alertWithTitle:@"Prompt"
                                               message:@"Prompt After deleting this event, other club members will also lose it permanently, confirming the continuation of the operation"
                                           cancelTitle:@"Reconsider"
                                          confirmTitle:@"Confirm"];
    [alert setOnOkAction:^{
            [weakSelf.hud showWithMaskType:WSProgressHUDMaskTypeClear];
        [JCClubApi deleteEventWithID:_eventArray[indexPath.row].eventID complete:^(NSError *error) {
                if (error) {
                    [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
                }else{
                    [weakSelf.hud dismiss];
                    [weakSelf.eventArray removeObjectAtIndex:indexPath.row];
                    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                }
            }];
    }];
    [alert show];
}

#pragma mark -- ScrollView代理
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _tableView) {
        [UIView animateWithDuration:0.3 animations:^{
            _pushBtn.alpha = 0;
        }];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == _tableView) {
        [UIView animateWithDuration:0.3 animations:^{
            _pushBtn.alpha = 1;
        }];
    }
}

- (IBAction)joinClubAction:(UIButton *)sender {
    if (self.joinClubAction) {
        self.joinClubAction();
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:kSegueClubPushEventDetail]) {
        JCEventDetailVC *vc = [segue destinationViewController];
        vc.eventModel = sender;
    }else if ([segue.identifier isEqualToString:kSegueClubPushEventExplain]){
        
    }
}


@end
